package com.book.iphone;

import com.book.book.domain.*;
import com.book.book.service.*;
import com.book.common.utils.R;
import com.book.iphone.domain.*;
import com.book.oa.domain.Message;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.apache.velocity.runtime.directive.Foreach;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.expression.spel.ast.NullLiteral;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 个人中心控制器
 * Created by siyuan on 2018/1/29.
 */
@Controller
@RequestMapping("/iphone")
public class userInfoController {

    @Autowired
    UsersService usersService;
    @Autowired
    BookService bookService;
    @Autowired
    BooksService booksService;
    @Autowired
    ApplyService applyService;
    @Autowired
    IndustryService industryService;
    @Autowired
    CategoryService categoryService;
    @Autowired
    AppointmentService appointmentService;
    @Autowired
    MessageService messageService;
    @Autowired
    WantSeeService wantSeeService;
    @Autowired
    QueueService queueService;
    @Autowired
    BooklogService booklogService;
    /***
     * 获取用户个中心信息
     */
    @RequestMapping(value = "/userInfo/{userId}", method = RequestMethod.GET)
    String getUserInfo(Model model, @PathVariable String userId, HttpServletRequest request) {
        //得到用户信息
        UsersDO usersDO = (UsersDO) request.getSession().getAttribute("userInfo");
        if (usersDO != null) {
            UsersDO usersDO1 = usersService.get(usersDO.getOpenId());
            model.addAttribute("userinfo", usersDO);
        } else {
            return "Redirect:/iphone/login";
        }

        //获得职业的信息
        List<IndustryDO> industryDOS = industryService.list(new HashMap<>());
        model.addAttribute("industryDOS", industryDOS);
        return "book/phone/html/person_info";
    }


    /**
     * 关注图书--列表
     */
    @GetMapping("/attention/{userid}")
    String getAttentions(Model model, @PathVariable String userid) {
        return "book/phone/html/addBookNumber";
    }

    /**
     * 举报
     */
    @GetMapping("/report/{userid}")
    String ToReport(Model model, @PathVariable String userid) {
        model.addAttribute("userid", userid);
        return "book/phone/html/report";

    }

    /**
     * 漂流图书列表
     * 使用userid查
     * 获取到在用户手里的所有属于漂流的图书
     * 漂流日志表
     */
    @GetMapping("/driftList/{userid}")
    String getPiaoliu(Model model, @PathVariable String userid) {
        Map<String,Object> logmap=new HashMap<>();
        logmap.put("userId",userid);
        logmap.put("sentimentText",userid);
        List<DriftDo> driftDos=booklogService.getDrift(logmap);
        if (driftDos.size()!=0){
            for (int i=0;i<driftDos.size();i++){
                String img=driftDos.get(i).getBookImg();
                if (img==null || img.equals("")){

                }else {
                    driftDos.get(i).setBookImg(img.split(",")[0]);
                }
            }
            model.addAttribute("driftDos",driftDos);
        }else {
            model.addAttribute("driftDos",null);
        }
        return "book/phone/html/drift_list";
    }

    /**
     * 由首页进入漂流图书列表
     * 判断是否已经验证信息
     */

    @RequestMapping("/toDriftList")
    String toDriftlist(HttpServletRequest request, Model model) {

        UsersDO usersDO = (UsersDO) request.getSession().getAttribute("userInfo");
        if (usersDO != null)  //验证用户信息
        {
            List<BooksDO> booksDOList = booksService.getbooks(usersDO.getOpenId());
            if (booksDOList.size() == 0) {
                model.addAttribute("userbooks", null);
            } else {
                model.addAttribute("userbooks", booksDOList);
            }
        } else {
            return "redirect:/iphone/login";
        }
        return "book/phone/html/drift_list";
    }

    /**
     * 已预约（待接收界面）
     * 列表
     * 待接收：预约后还未到手的书籍
     * 根据userId查询预约表
     */
    @RequestMapping("/receving/{userid}")
    String receving(@PathVariable("userid") String userId, Model model) {
        Map<String, Object> map = new HashMap<>();
        map.put("userId", userId);
        model.addAttribute("userId", userId);
        List<RecevingDo> recevingDoList = appointmentService.RecevingList(map);
        if (recevingDoList.size() == 0) {
            model.addAttribute("recevingDoList", null);
        } else {
            for (RecevingDo recevingDo : recevingDoList) {
                if (recevingDo.getBookImg() != null || recevingDo.equals("")) {
                    recevingDo.setBookImg(recevingDo.getBookImg().split(",")[0]);
                }
            }//拿到图书的图片地址 ....，....，....  取第一张图片
            model.addAttribute("recevingDoList", recevingDoList);
        }
        return "book/phone/html/receving_note";
    }

    /**
     * 预约表删除，可预约数加一
     * 将该用户的信息从预约队列中删除
     * 先从队列中移除信息，在删除表中信息
     *
     * @param id
     * @param request
     * @return
     */
    @RequestMapping("/delectYuyue/{id}")
    @ResponseBody
    R delectYuyue(@PathVariable("id") int id, HttpServletRequest request) {
        AppointmentDO appointmentDO = appointmentService.get(id);
        String userId=appointmentDO.getUserId();
        String bookfName=appointmentDO.getBookName();
        List<QueueDO> queueDOList = queueService.getQueueItem(userId,bookfName);
        int ok=0;
        Gson gson=new Gson();
        for (int i=0;i<queueDOList.size();i++){
            boolean flag=false;//是否已经删除数据
            String jsonStr=queueDOList.get(i).getQueue();
            List<QueueListItem> items=gson.fromJson(jsonStr,new TypeToken<List<QueueListItem>>(){}.getType());
            for (int j=0;j<items.size();j++){
                if (items.get(j).getUserId().equals(appointmentDO.getUserId())){
                    items.remove(items.get(j));
                    flag=true;
                }
            }
            if (flag){
                String queueJson=gson.toJson(items);
                queueDOList.get(i).setQueue(queueJson);
                ok=queueService.update(queueDOList.get(i));
            }
        }
        if (ok==1){
            int a = appointmentService.remove(id);
            if (a == 1) {
                UsersDO usersDO = usersService.getopenid(appointmentDO.getUserId());
                usersDO.setBorrowNum(usersDO.getBorrowNum() + 1);
                usersService.update(usersDO);
                request.getSession().setAttribute("userInfo", usersDO);
                return R.ok("删除成功");
            }else {
                return R.error("删除失败");
            }
        }else {
            return R.error("删除失败");
        }
    }

    /**
     * 根据userId查询所有用户提交的图书（包括申请通过和未通过的）
     * 贡献图书列表
     *
     * @param userId
     */
    @GetMapping("/listallapply/{userId}")
    String listAllApply(@PathVariable("userId") String userId, Model model) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("userId", userId);
        List<ApplyDO> applyDOList = applyService.listAllByUserId(map);
        model.addAttribute("userId", userId);
        if (applyDOList.size() == 0) {
            model.addAttribute("applyDOList", null);
        } else {
            model.addAttribute("applyDOList", applyDOList);
        }

        return "book/phone/html/contribution_list";
    }

    /**
     * 跳转贡献图书
     */
    @RequestMapping("/toContribution/{userid}")
    String gotocontribution(@PathVariable String userid, Model model) {
        //获得系统的图书类别
        List<CategoryDO> categoryDOS = categoryService.list(new HashMap<>());
        model.addAttribute("categoryDOS", categoryDOS);
        model.addAttribute("userid", userid);
        return "book/phone/html/contribution";
    }

    /**
     * 由心愿列表跳转贡献图书
     */
    @RequestMapping("/toContribution")
    String gotoWashcontribution(Model model, HttpServletRequest request) {
        String userid = null;
        //获得系统的图书类别
        List<CategoryDO> categoryDOS = categoryService.list(new HashMap<>());
        UsersDO usersDO = (UsersDO) request.getSession().getAttribute("userInfo");
        if (usersDO == null)  //验证用户信息
        {
            return "redirect:/iphone/login";
        }
        userid = usersDO.getUserId();
        model.addAttribute("categoryDOS", categoryDOS);
        model.addAttribute("userid", userid);
        return "book/phone/html/contribution";
    }

    /**
     * 图书--书架
     */
    @RequestMapping("/mybook/{userid}")
    String mybook(Model model, @PathVariable String userid) {
        List<BooksDO> booksDOList = booksService.getbooks(userid);
        if (booksDOList.size() == 0) {
            model.addAttribute("userbooks", null);
        } else {
            model.addAttribute("userbooks", booksDOList);
        }
        return "book/phone/html/mybook_list";
    }

    /**
     * 系统通知
     */
    @RequestMapping("/SysMessage/{userid}")
    String SysMessage(Model model, @PathVariable String userid) {
        Map<String, Object> map = new HashMap<>();
        map.put("userId", userid);
        List<MessageDO> messageDOList = messageService.list(map);
        if (messageDOList.size() == 0) {
            model.addAttribute("messageDOList", null);
        } else {
            for (MessageDO messageDO : messageDOList) {
                messageDO.setRedundance1(messageDO.getUserMessage().substring(0, 5) + "...");
            }
            model.addAttribute("messageDOList", messageDOList);
        }
        return "book/phone/html/sys_msg";
    }

    /**
     * 删除系统通知
     */
    @RequestMapping("/message/delete/{id}/{userId}")
    public String DeleteMessage(@PathVariable("id") int id, @PathVariable("userId") String userId, Model model) {

        messageService.remove(id);
        Map<String, Object> map = new HashMap<>();
        map.put("userId", userId);
        List<MessageDO> messageDOList = messageService.list(map);
        if (messageDOList.size() == 0) {
            model.addAttribute("messageDOList", null);
        } else {
            for (MessageDO messageDO : messageDOList) {
                messageDO.setRedundance1(messageDO.getUserMessage().substring(0, 5) + "...");
            }
            model.addAttribute("messageDOList", messageDOList);
        }
        return "book/phone/html/sys_msg";
    }

    /**
     * 问题反馈界面
     *
     * @param model
     * @param userid
     * @return
     */
    @RequestMapping("/perblem/{userid}")
    String perblem(Model model, @PathVariable String userid) {
        return "book/phone/html/problem";
    }

    /**
     * 个人信息
     */
    @RequestMapping(value = "/commitPersonInfo/{userid}", method = RequestMethod.POST)
    String CommitInfo(UserInfo userInfo, @PathVariable("userid") String userid) {
        UsersDO usersDO = usersService.getopenid(userid);
        if (usersDO != null) {
            if (!userInfo.getProvince().equals("省份") && !userInfo.getCity().equals("城市")) {
                usersDO.setAddress(userInfo.getProvince().split(",")[1] +
                        userInfo.getCity().split(",")[1] +
                        userInfo.getDistrict()
                        + (usersDO.getAddress() == null ? "" : usersDO.getAddress()));
            }
            usersDO.setUserId(userid);
            usersDO.setBirthday(userInfo.getBirth());
            usersDO.setIndustryId(Math.toIntExact(userInfo.getDeptId()));
            usersDO.setMotto(userInfo.getMotto());
            usersDO.setPhone(userInfo.getPhone());
            usersDO.setSex(userInfo.getSex());
            usersDO.setPersonalDescription(userInfo.getDescription());
            int aa = usersService.update(usersDO);
        }
        return "redirect:/iphone/user";
    }

    /**
     * 心愿单提交
     * 查看个人的用户心愿表单列表
     *
     * @param wantSeeDO
     * @return
     */
    @RequestMapping("/washSubmit")
    public String wish(WantSeeDO wantSeeDO, Model model, HttpServletRequest request) {
        if (wantSeeDO.getBookName() == null || wantSeeDO.getUserId() == null) {

            UsersDO usersDO = (UsersDO) request.getSession().getAttribute("userInfo");
            if (usersDO != null) {
                String userId = null;
                userId = usersDO.getOpenId();
                List<WashDo> wantSeeDOList = wantSeeService.listPersonalWishByUserId(userId);
                if (wantSeeDOList.size() != 0) {
                    model.addAttribute("wantSeeDOList", wantSeeDOList);
                } else {
                    model.addAttribute("wantSeeDOList", null);
                }
            } else {
                return "redirect:/iphone/login";//重定向到登录
            }
        } else {
            wantSeeDO.setCreateTime(new Date());
            Map<String, Object> find = new HashMap<>();
            find.put("bookName", wantSeeDO.getBookName());
            List<WantSeeDO> wantSeeDO1 = wantSeeService.list(find);
            if (wantSeeDO1.size() == 0) {
                wantSeeService.save(wantSeeDO);
            }
            Map<String, Object> map = new HashMap<>();
            map.put("userId", wantSeeDO.getUserId());
            List<WashDo> wantSeeDOList = wantSeeService.listPersonalWishByUserId(wantSeeDO.getUserId());
            if (wantSeeDOList.size() != 0) {
                model.addAttribute("wantSeeDOList", wantSeeDOList);
            } else {
                model.addAttribute("wantSeeDOList", null);
            }
        }
        return "book/phone/html/wash_list";
    }

    /**
     * @param model
     * @return
     */
    @RequestMapping("/awishList")
    String washList(Model model) {
        List<WashDo> wantSeeDOList = wantSeeService.listPersonalWishByUserId(null);
        if (wantSeeDOList.size() != 0) {
            model.addAttribute("wantSeeDOList", wantSeeDOList);
        } else {
            model.addAttribute("wantSeeDOList", null);
        }
        return "book/phone/html/wash_list";
    }

    @RequestMapping("/wash")
    String wish(String userId, String userImg, Model model) {
        model.addAttribute("userId", userId);
        model.addAttribute("userImg", userImg);
        return "book/phone/html/wash";
    }

    /**
     * 心愿的详细信息
     */
    @RequestMapping("/wishInfo/{id}")
    String WishInfo(@PathVariable int id, Model model) {
        int a = id;
        WantSeeDO wantSeeDO = wantSeeService.get(id);
        model.addAttribute("wantSeeDO", wantSeeDO);
        return "book/phone/html/washInfo";
    }
}






